package com.star.springai.chat.service;

import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;

/**
 * 将MultipartFile包装成Spring Resource接口的实现
 */
public class MultipartFileResource implements Resource {
    
    private final MultipartFile multipartFile;
    
    public MultipartFileResource(MultipartFile multipartFile) {
        this.multipartFile = multipartFile;
    }
    
    @Override
    public boolean exists() {
        return multipartFile != null && !multipartFile.isEmpty();
    }
    
    @Override
    public boolean isReadable() {
        return exists();
    }
    
    @Override
    public boolean isOpen() {
        return false;
    }
    
    @Override
    public boolean isFile() {
        return false;
    }
    
    @Override
    public URL getURL() throws IOException {
        throw new UnsupportedOperationException("MultipartFileResource does not support getURL()");
    }
    
    @Override
    public URI getURI() throws IOException {
        throw new UnsupportedOperationException("MultipartFileResource does not support getURI()");
    }
    
    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(multipartFile.getBytes());
    }
    
    @Override
    public long contentLength() throws IOException {
        return multipartFile.getSize();
    }
    
    @Override
    public long lastModified() throws IOException {
        return System.currentTimeMillis();
    }
    
    @Override
    public Resource createRelative(String relativePath) throws IOException {
        throw new UnsupportedOperationException("MultipartFileResource does not support createRelative()");
    }
    
    @Override
    public String getFilename() {
        return multipartFile.getOriginalFilename();
    }
    
    @Override
    public String getDescription() {
        return "MultipartFile resource [" + multipartFile.getOriginalFilename() + "]";
    }
    
    @Override
    public File getFile() throws IOException {
        throw new UnsupportedOperationException("MultipartFileResource does not support getFile()");
    }
}
